package cn.zcy.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

public class MyBatisConfig {

    /**
     * 使用spring的el表达式赋值
     */
    @Value("${jdbc.driver}")
    private String driver;
    /**
     * 使用spring的el表达式赋值
     */
    @Value("${jdbc.url}")
    private String url;
    /**
     * 使用spring的el表达式赋值
     */
    @Value("${jdbc.username}")
    private String username;
    /**
     * 使用spring的el表达式赋值
     */
    @Value("${jdbc.password}")
    private String password;

    /**
     * 1.集成SqlSessionFactoryBean，就是用来构建SqlSessionFactory，用来读取Mybatis的信息设置到configuration中
     * 2.集成Spring的声明式事务。。。。实际上就是拿到spring开始事务事 创建的connection
     * @param dataSource
     * @return
     * @throws IOException
     */
    @Bean
    public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource) throws IOException {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        // 设置 MyBatis 配置文件路径
        factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        // 设置 SQL 映射文件路径
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:cn/zcy/mapper/*.xml"));

        return factoryBean;
    }

    /**
     * 创建数据源，并存入IOC容器
     *
     * @return
     */
    @Bean
    public DataSource createDateSource() throws Exception {
        //数据源
//        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    /**
     * 创建平台事务管理器器
     *
     * @param dataSource
     * @return
     */
    @Bean
    public PlatformTransactionManager getTransactionManager(@Autowired DataSource dataSource) {

        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
        return dataSourceTransactionManager;
    }

}
